<template>
  <view class="container">
    <view class="postx" :style="scrollTop>0?'background:#FFF;':''">
      <view :style="'height:'+statusBarHeight+'px'"></view>
      <view class="flexJusp" style="font-size: 36rpx;font-weight: bold;text-align: center;padding:0 20rpx;"
            :style="'height:'+navigationBarHeight+'px;line-height:'+navigationBarHeight+'px'">
        <view style="width:50rpx;" @click="back">
          <image style="width:20rpx;height:34rpx;" src="/static/image/mv_tuichu.png"></image>
        </view>
        <view>确认订单</view>
        <view style="width:50rpx;"></view>
      </view>
    </view>
    <view style="width: 750rpx;height: 650rpx;background: linear-gradient(228deg,#CCEAFF,#F9FBFC);">
      <view :style="'height:'+statusBarHeight+'px'"></view>
      <view :style="'height:'+navigationBarHeight+'px'"></view>
      <view class="flex" style="margin-top:32rpx;" v-if="orderDetail.username">
        <image style="width:34rpx;height:42rpx;margin:34rpx 34rpx 0 40rpx;" src="/static/image/02_1gb.png">
        </image>
        <view @tap="chooseAddress">
          <view>
            <text style="font-size: 30rpx;font-weight: bold;margin-right:20rpx;">
              {{ orderDetail.username }}
            </text>
            {{ orderDetail.phone }}
          </view>
          <view style="width: 540rpx;font-size: 26rpx;color: #4E4E4E;">
            {{ orderDetail.addressdetail }}
          </view>
        </view>
      </view>
      <view class="flex_new" v-if="!orderDetail.username" @tap="chooseAddress">
        <image style="width:34rpx;height:42rpx; margin: auto 20px auto 60rpx;" src="/static/image/02_1gb.png">
          <view class="text">新增客户地址</view>
          <image style="width:16rpx;height: 24rpx; margin: auto 10px auto 350rpx;"
                 src="/static/image/mv_tuichus.png"></image>
        </image>
      </view>

      <image style="width: 100%;height:4rpx;" src="/static/image/02_1c.png"></image>
      <view style="width: 670rpx;background: #FFFFFF;border-radius: 20rpx;margin:20rpx;padding:16rpx 20rpx 0rpx;"
            v-if="list.length > 0">
        <view style="font-size:26rpx;">商品信息</view>
        <view class="flex" v-for="(item,index) in list" :key="index" style="margin:12rpx 0 16rpx;">
          <image style="width: 164rpx;height: 150rpx;border-radius: 12rpx;" :src="item.img"></image>
          <view style="width:490rpx;margin-left:16rpx;">
            <view style="font-weight: bold;">{{ item.goodsname }}</view>
            <view class="flexJusp" style="font-size:24rpx;color: #666666;margin:10rpx 0;">
              <view>服务项目：{{ item.xiangmu }}</view>
              <view>×{{ item.number }}</view>
            </view>
          </view>
        </view>
      </view>
      <view style="background: #FFFFFF;border-radius: 20rpx;margin:0 20rpx;padding:20rpx;font-size:26rpx;">
        <view v-if="orderDetail.moshi !=4">
          <view class="flexJusp" style="line-height:58rpx;margin-top:20rpx;">
            <view style="color: #333;font-weight: bold;">期望上门时间</view>
            <picker mode="date" :value="orderDetail.qitime" :start="startDate" :end="endDate" @change="bindDateChange">
              <view :style="orderDetail.qitime?'color:#333;':'color: #999999;'"
                    style="width: 140rpx;height: 34rpx;border-radius: 10rpx;border: 1rpx solid #666666;padding:12rpx 16rpx;font-size:24rpx;font-size: 24rpx;line-height: 34rpx;text-align: center;">
                {{ orderDetail.qitime || '选择时间' }}
              </view>
            </picker>
          </view>

        </view>
        <view class="flexJusp" style="height: 60rpx; line-height: 70rpx;" v-if="false">
          <view style="color: #666666;">优惠券</view>
          <view>-￥{{ couponNum }}</view>
        </view>
        <view class="flexJusp" v-if="orderDetail.moshi===1" style="height: 60rpx; line-height: 65rpx;">
          <view style="color: #666666;">订单总价</view>
          <view>￥{{ orderDetail.price }}</view>
        </view>
        <view class="flexJusp" style="line-height:58rpx;" v-if="orderDetail.moshi===2">
          <view style="color: #333;font-weight: bold; line-height:100rpx;">期望价格</view>
          <view class="flex" style="margin-top: 20rpx;">
            <input v-model="orderDetail.qiprice" type="digit"
                   style="width: 170rpx;height: 34rpx;border-radius: 10rpx;border: 1rpx solid #666666;padding:10rpx 14rpx;font-size:22rpx;"
                   placeholder="请设置期望价格"/>
            <view style="margin-left:16rpx;">元</view>
          </view>
        </view>
        <view v-if="orderDetail.moshi===2" style="color: #666666;margin-top:10rpx;"></view>

        <view class="flexJusp" style="line-height:110rpx;display: flex;" v-if="orderDetail.moshi===3">
          <view style="color: #333;font-weight: bold;">悬赏金额</view>
          <view class="flex" style="display: flex; align-items: center;">
            <input v-model="orderDetail.xuanshangprice" type="digit"
                   style="width: 170rpx;height: 34rpx;border-radius: 10rpx;border: 1rpx solid #666666;padding:10rpx 14rpx;font-size:22rpx;text-align: center;"
                   placeholder="请设置悬赏金额" :disabled="xiadan"/>
            <view style="margin-left:16rpx;">元</view>
          </view>
        </view>
        <view class="flexJusp" style="line-height:58rpx; margin-top:20rpx;" v-if="orderDetail.moshi===4">
          <view style="color: #333;font-weight: bold;">所需人数</view>
          <view class="flex">
            <input v-model="orderDetail.xunumber" type="number" :disabled="xiadan"
                   style="width: 170rpx;height: 34rpx;border-radius: 10rpx;border: 1rpx solid #666666;padding:6rpx 8rpx;font-size:24rpx;text-align: right;"
                   placeholder="请输入"/>
            <view style="margin-left:16rpx;">人</view>
          </view>
        </view>
        <view class="flexJusp" style="line-height:58rpx;margin-top:20rpx;" v-if="orderDetail.moshi==4">
          <view style="color: #333;font-weight: bold;">小时价格</view>
          <view class="flex">
            <input v-model="orderDetail.xuprice" type="digit" :disabled="xiadan"
                   style="width: 140rpx;height: 34rpx;border-radius: 10rpx;border: 1rpx solid #666666;padding:12rpx 16rpx;font-size:24rpx;font-size: 24rpx;line-height: 34rpx;text-align: center;"
                   placeholder="请设置小时价格"/>
            <view style="margin-left:16rpx;">元/小时</view>
          </view>
        </view>
        <view class="flexJusp" style="line-height:58rpx;margin-top:20rpx;" v-if="orderDetail.moshi==4">
          <view style="color: #333;font-weight: bold;">上门时间段</view>
          <u-datetime-picker text="起始时间" ref="startTime" @timeChange="startTimeChange($event)"
                             style="border-radius: 10rpx;border: 1rpx solid #666666;height: 50rpx;width: 30%;padding: 10rpx;"
                             :disabled="xiadan">

          </u-datetime-picker>

          <u-datetime-picker text="结束时间" ref="endTime" @timeChange="endTimeChange($event)"
                             style="border-radius: 10rpx;border: 1rpx solid #666666;height: 50rpx;width: 30%;padding: 10rpx;"
                             :disabled="xiadan">

          </u-datetime-picker>
        </view>
        <view v-if="orderDetail.moshi===4" style="color: #666666;margin-top:10rpx;text-align: right;">
          共计{{ orderDetail.duration }}小时，总计订单金额
          {{ (orderDetail.xuprice * orderDetail.duration * orderDetail.xunumber).toFixed(2) + '元' || '未选择完成' }}
        </view>
      </view>

      <view style="font-size: 26rpx;color: #333333;margin:24rpx 28rpx 0;">温馨提示</view>
      <view style="font-size: 24rpx;color: #666666;margin:0 28rpx;">修改金额请重新下单</view>
      <view style="display: flex; justify-content: space-around;">
        <view class="buttons" @click="complete">{{ xiadan ? '继续支付' : '立即提交' }}</view>
      </view>
      <view style="height:env(safe-area-inset-bottom);"></view>
    </view>
  </view>
</template>

<script>
import {systemInfo} from '@/https/mixin.js'

export default {
  mixins: [systemInfo],
  data() {
    return {
      scrollTop: 0,
      startDate: '',
      endDate: '', // 结束日期
      orderDetail: {},
      couponNum: 0,
      coupons_id: '',
      xiadan: false,
      list: [{
        img: '',
        goodsname: '',
        xiangmu: '',
        number: '',
      }],
      scan: false,
      clicked: false,
      currentAddress: {},
    }
  },
  onLoad(option) {
    this.orderDetail.orderId = option.id
    if (option.scan) {
      this.scan = option.scan === 'true'
      this.loadDetail()
    } else {
      this.orderDetail.moshi = Number(option.moshi);
      this.orderDetail.limu = option.limu
      this.orderDetail.price = Number(option.price)
    }
    this.selectAddress()
    if (option.couponNum) {
      this.couponNum = option.couponNum
    }

    this.getSystemInfo()
  },
  created() {
    // 获取当前时间
    const currentDate = new Date();
    // 设置开始时间为当前时间
    this.startDate = currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate();
    // 设置结束时间
    const endDate = new Date(currentDate.getFullYear() + 20, currentDate.getMonth(), currentDate.getDate());
    this.endDate = endDate.getFullYear() + '-' + (endDate.getMonth() + 1) + '-' + endDate.getDate();
  },
  onPageScroll(event) {
    this.scrollTop = event.scrollTop // 获取当前页面滚动高度
  },
  mounted() {
    let date = new Date()
    let dateTimeValue =
        `${date.getFullYear()}-${this.withDate(date.getMonth() + 1)}-${this.withDate(date.getDate())} ${this.withDate(date.getHours())}`

    this.startTimeChange(dateTimeValue)
    this.endTimeChange(dateTimeValue)
  },
  methods: {
    selectAddress() {
      this.$httpapi('selectAddress', 'POST', {}).then(res => {
        // 地址数组
        if (res.data.length > 0) {
          this.bindAddress(res.data[0])
          for (let i = 0; i < res.data.length; i++) {
            if (res.data[i].area_status === '1') {
              this.bindAddress(res.data[i])
              break
            }
          }
        }
      }).catch(selectAddressErr => {
        console.error('Error in selectAddress:', selectAddressErr);
      });
      this.list = uni.getStorageSync('list')
    },
    // 地址选择
    chooseAddress() {
      uni.navigateTo({
        url: '/pages_user/user/address/address?type=2',
        events: {
          acceptDataFromOpenedPages: (data) => {
            if (data) {
              this.bindAddress(data)
            } else {
              this.selectAddress()
            }
          },
        },
      })
    },
    bindAddress(address) {
      this.currentAddress = address
      this.orderDetail.username = address.username;
      this.orderDetail.ordername = address.username;
      this.orderDetail.address = address.area_name;
      this.orderDetail.area = address.area;
      this.orderDetail.latitude = address.latitude;
      this.orderDetail.longitude = address.longitude;
      this.orderDetail.phone = address.phone;
      this.orderDetail.orderphone = address.phone;
      this.orderDetail.addressdetail = address.area_detaile;
      this.$forceUpdate()
    },
    loadDetail() {
      this.$httpapi('orderdetail', 'POST', {
        orderId: this.orderDetail.orderId
      }).then(res => {
        this.orderDetail = res.data
        this.orderDetail.moshi = Number(this.orderDetail.moshi)
        this.list = res.data.xiangmu
        this.bindAddress(this.currentAddress)
        this.orderDetail.orderId = this.orderDetail.order_id
      })
    },
    bindDateChange(e) {
      this.orderDetail.qitime = e.detail.value
      this.$forceUpdate()
    },
    startTimeChange(event) {
      this.orderDetail.starttime = event
      if (this.orderDetail.starttime && this.orderDetail.starttime.length > 0 &&
          this.orderDetail.endtime && this.orderDetail.endtime.length > 0) {
        const startDate = new Date(this.orderDetail.starttime + ":00:00");
        const endDate = new Date(this.orderDetail.endtime + ":00:00");

        // 计算时间间隔的毫秒数
        const intervalInMilliseconds = endDate.getTime() - startDate.getTime();
        if (intervalInMilliseconds < 0) {
          this.orderDetail.duration = 0
          uni.showToast({
            title: '请选择正确的时间段',
            icon: 'none'
          })
        } else {
          // 将毫秒数转换为小时、分钟或秒
          const hours = intervalInMilliseconds / (1000 * 60 * 60);
          this.orderDetail.duration = hours
        }
      } else {
        this.orderDetail.duration = 0
      }
      this.$forceUpdate()
    },
    endTimeChange(event) {
      this.orderDetail.endtime = event
      if (this.orderDetail.starttime && this.orderDetail.starttime.length > 0 &&
          this.orderDetail.endtime && this.orderDetail.endtime.length > 0) {
        const startDate = new Date(this.orderDetail.starttime + ":00:00");
        const endDate = new Date(this.orderDetail.endtime + ":00:00");

        // 计算时间间隔的毫秒数
        const intervalInMilliseconds = endDate.getTime() - startDate.getTime();
        if (intervalInMilliseconds < 0) {
          this.orderDetail.duration = 0
          uni.showToast({
            title: '请选择正确的时间段',
            icon: 'none'
          })
        } else {
          // 将毫秒数转换为小时、分钟或秒
          const hours = intervalInMilliseconds / (1000 * 60 * 60);
          this.orderDetail.duration = hours
        }
      } else {
        this.orderDetail.duration = 0
      }
      this.$forceUpdate()
    },
    coupon() {
      // var that = this
      // uni.navigateTo({
      // 	url: '/pages/PlaceOrder/coupon/coupon?type=' + this.moshi + '&kind=2',
      // 	events: {
      // 		acceptDataFromOpenedPages: (data) => {
      // 			console.log(data, '---------')
      // 			this.couponNum = data.manprice
      // 			this.coupons_id = data.coupons_id
      // 		},
      // 	},
      // })
    },
    withDate(param) {
      return param < 10 ? '0' + param : '' + param;
    },
    async complete() {
      if (this.clicked) {
        return
      }
      this.clicked = true
      setTimeout(() => {
        this.clicked = false;
      }, 1500); // 设置等待时间，例如 1.5 秒
      if (!this.orderDetail.address) {
        uni.showToast({
          title: '请选择地址',
          icon: 'none'
        });
        return;
      }
      if (this.orderDetail.moshi !== 4 && !this.orderDetail.qitime) {
        uni.showToast({
          title: '请选择上门时间',
          icon: 'none'
        })
        return
      }
      if (this.orderDetail.moshi === 3) {
        if (!this.orderDetail.xuanshangprice || this.orderDetail.xuanshangprice <= 0) {
          uni.showToast({
            title: '请填写悬赏金额',
            icon: 'none'
          })
          return
        }
        this.orderDetail.price = this.orderDetail.xuanshangprice
      } else if (this.orderDetail.moshi === 4) {
        if (!this.orderDetail.xunumber || this.orderDetail.xunumber === '' || this.orderDetail.xunumber <= 0) {
          uni.showToast({
            title: '请填写正确的用工人数',
            icon: 'none'
          })
          return
        }
        if (!this.orderDetail.xuprice || this.orderDetail.xuprice === '' ||
            this.orderDetail.xuprice <= 0) {
          uni.showToast({
            title: '请填写正确的金额',
            icon: 'none'
          })
          return
        }
        if (this.orderDetail.duration <= 0) {
          uni.showToast({
            title: '请选择正确的时间段',
            icon: 'none'
          })
          return
        }
        this.orderDetail.price = this.orderDetail.xuprice * this.orderDetail.duration * this.orderDetail.xunumber
      }
      let res = {}
      if (this.xiadan || this.scan) {
        let bindRes = await this.bindorder();
        if (bindRes.code == 200) {
          res = await this.addPackageListAPI();
        }
      } else {
        let preorderRes = await this.preorder();
        if (preorderRes.code == 200) {
          this.orderDetail.orderId = preorderRes.data; // 设置订单 ID
          res = await this.addPackageListAPI();
        }
      }
      this.$utils.saveSyncTime()
      if (!res || res.code != 200) {
        uni.showToast({
          title: '下单失败',
          icon: 'none'
        })
        return
      }
      if (res.code != 200) {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
        return
      }
      if (res.data) {
        this.xiadan = true;
        if (res.data.status === 1) {
          uni.switchTab({
            url: '/pages/myOrder/myOrder'
          })
        } else {
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success: function (rexx) {
              uni.removeStorageSync('list');
              uni.redirectTo({
                url: '/pages/PlaceOrder/confirmOrder/payment'
              })
            },
            fail: function (err) {
            }
          });
        }
      } else {
        if (this.orderDetail.moshi === 2) {
          uni.switchTab({
            url: '/pages/myOrder/myOrder'
          })
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      }
    },
    async addPackageListAPI() {
      // 付款
      this.orderDetail.yuchatime = this.orderDetail.duration
      this.orderDetail.fentime = this.orderDetail.starttime + ',' + this.orderDetail.endtime
      let res = await this.$httpapi('addPackageList', 'POST', this.orderDetail)
      if (res.code !== 200) {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
      return res
    },
    async bindorder() {
      let res = await this.$httpapi('bindorder', 'POST', this.orderDetail)
      if (res.code !== 200) {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
      return res;
    },
    async preorder() {
      for (let i = 0; i < this.list.length; i++) {
        this.list[i].huanimg = this.list[i].huanimgList.toString()
      }
      let xiangmuFlag = '';
      for (let i = 0; i < this.list.length; i++) {
        if (i === 0) xiangmuFlag += '[' + this.list[i].xiangmuid + ']'
        else xiangmuFlag += ',[' + this.list[i].xiangmuid + ']'
      }
      this.orderDetail.xiangmuflag = xiangmuFlag
      this.orderDetail.list = this.list

      let res = this.$httpapi('preorder', 'POST', this.orderDetail)
      if (res.code !== 200) {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
      return res
    }
    ,
    quotation() {
      uni.navigateTo({
        url: '/pages/myOrder/QuotationList/QuotationList'
      })
    }
    ,
    back() {
      // 获取当前页面栈的实例
      const pages = getCurrentPages();

      // 获取页面栈的长度
      const stackLength = pages.length;

      // 判断是否有可回退的页面
      if (stackLength > 1) {
        // 存在可回退的页面，可以执行回退操作
        uni.navigateBack()
      } else {
        uni.switchTab({
          url: '/pages/PlaceOrder/PlaceOrder'
        })
      }
      uni.removeStorageSync('list');
    }
    ,
  }
}
</script>

<style lang="scss">
page {
  background-color: #F7F6FA;
}

.container {
  padding-bottom: 20rpx;
  color: #333333;

  .postx {
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99999999;
  }

  .flex_new {
    display: flex;
    height: 130rpx;

    .text {
      line-height: 130rpx;
    }
  }

  .buttons {
    margin: 100rpx auto 0;
    text-align: center;
    width: 710rpx;
    height: 83rpx;
    background: linear-gradient(180deg, #2089FF 0%, #11ACEF 100%);
    border-radius: 44rpx;
    font-size: 27rpx;
    color: #FFFFFF;
    line-height: 83rpx;
  }

  .posts {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 99;
    width: 710rpx;
    padding: 16rpx 20rpx;
    background-color: #FFF;
    box-shadow: 0rpx -4rpx 12rpx 2rpx rgba(0, 0, 0, 0.04);

    .buttonx {
      text-align: center;
      width: 188rpx;
      height: 60rpx;
      border-radius: 32rpx;
      border: 2rpx solid #666666;
      font-size: 26rpx;
      color: #666666;
      line-height: 60rpx;
    }
  }
}
</style>
